package com.learn.java3y.java.collection;


import java.util.Arrays;

/**
 * 模拟写时复制的场景
 */
public class CopyOnWriteArrayListTest {

    private Integer[] array;

    public static void main(String[] args) {
        CopyOnWriteArrayListTest listTest = new CopyOnWriteArrayListTest();
        listTest.array = new Integer[]{1, 2, 3};
        ObjectTest objectTest = new ObjectTest(listTest.array);
        // 写时复制
        listTest.add(4);
        objectTest.show();
    }

    public boolean add(Integer e) {
        Integer[] elements = this.array;
        int len = elements.length;
        System.out.printf("old array %s%n", this.array.hashCode());
        Integer[] newElements = Arrays.copyOf(elements, len + 1); // 复制出一个新数组
        newElements[len] = e; // 添加时，将新元素添加到新数组中
        this.array = newElements; // 将 volatile Object[] array 的指向替换成新数组
        System.out.printf("this array %s%n", this.array.hashCode());
        return true;
    }

    static final class ObjectTest {
        private Integer[] snapshot;

        public ObjectTest(Integer[] snapshot) {
            this.snapshot = snapshot;
        }

        public void show() {
            System.out.printf("snapshot %s%n", snapshot.hashCode());
            Arrays.stream(snapshot).forEach(System.out::println);
        }
    }

}
